﻿using System;
using System.Collections.Generic;
using System.Reflection;
using Company.Merchandising.BusinessLayer.DataEntities;
using Company.Merchandising.BusinessLayer.DataTransferObjects;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;

namespace Company.Merchandising.ServiceLayer.Faculties.FacultiesManagement
{
	public class FacultyManager
	{
		public static void InitializeFaculties()
		{
			Assembly[] loadedAssemlbies = AppDomain.CurrentDomain.GetAssemblies();
			using (MerchModelEntities modelEntities = new MerchModelEntities())
			{
				DACFaculty dacFaculty = new DACFaculty(modelEntities);
				var facultiesNumber = dacFaculty.GetNumberOfFaculties();
				if (facultiesNumber > 0)
				{
					return;
				}

				List<DTOFaculty> faculties = new List<DTOFaculty>();
				foreach (var assembly in loadedAssemlbies)
				{
					foreach (var module in assembly.GetModules(false))
					{
						foreach (var type in module.GetTypes())
						{
							foreach (FacultyActionAttribute attribute in type.GetCustomAttributes(typeof(FacultyActionAttribute), false))
							{
								faculties.Add(new DTOFaculty() { Name = attribute.FacultyName, Description = attribute.FacultyDescription });
							}
						}
					}
				}

				dacFaculty.AddFaculties(faculties);
			}
		}
	}
}
